<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * Class Ads
 * @author  heyu
 */
class Ads extends MY_Controller {
    /**
     * @var AdmAdsModel
     */
    public $mAds;
    public $position;
    /**
     * 产品分类
     * @var ConsumerCategoryModel
     */
    public $mCategory;

	public function __construct(){
		parent::__construct();
        $this->loadModel('AdmAdsModel', 'mAds');
        $this->loadModel('ConsumerCategoryModel', 'mCategory', 'consumer');
        $this->position = getCustomConfig('ads_position');
	}
	
	/**
	 * 首页
	 */
	public function index(){
        $category = $this->mCategory->getCategoryList(0, true);
        $data = array(
            'category' => $category,
            'title' => '广告管理'
        );
		$this->view('config/ads/img', $data, '');
	}

    /**
     * 广告列表
     */
    public function home(){
        $type = (int)get('type');
        if (!$type){
            show_404();
        }

        $data = array(
            'position' => $this->position[$type],
            'type' => $type,
            'title' => '广告列表'
        );
        $this->view('config/ads/home', $data, 'datatable,datepicker');
    }

    /**
     * 获取列表
     */
    public function getList(){
        $data = $this->mAds->adminPcGetList();
        $time = strtotime(date('Y-m-d', time()));
        foreach ($data['data'] as $k => $v){
            $data['aaData'][$k][] = '<img src="'.getImage($v['pic'],'xs').'" class="img-wh"/>';
//            $data['aaData'][$k][] = $this->position[$v['ads_position']];
            $data['aaData'][$k][] = $v['ads_name'];
//            $data['aaData'][$k][] = $v['cat_name'];
//            $data['aaData'][$k][] = isset($v['starttime']) ? dateFormat($v['starttime']) : '';
//            $data['aaData'][$k][] = isset($v['endtime']) ? dateFormat($v['endtime']) : '';
//
//            if ($v['endtime'] + 86400 > $time){
//                $status = 2;
//            }else{
//                $status = 1;
//            }
//            $data['aaData'][$k][] = $this->getStatus($status, true);
            if ($v['type'] == 1){
                $data['aaData'][$k][] = '外链：<span style="color:#0411ff">' .$v['url'].'</span>';
            }else if($v['type'] == 2 && $v['merchant_id'] > 0){
                $data['aaData'][$k][] = '商家：<span style="color:#0411ff">'.$v['merchant_name'].'</span>';
            }else if($v['type'] == 3){
                $data['aaData'][$k][] = $v['merchant_name'].'店铺内商品：<span style="color:#0411ff">'.$v['product_name'].'</span>';
            }else if($v['type'] == 4){
                $data['aaData'][$k][] = '分类：<span style="color:#0411ff">'.$v['cat_name'].'</span>';
            }else{
                $data['aaData'][$k][] = '';
            }
            $data['aaData'][$k][] = isset($v['addtime']) ? dateFormat($v['addtime']) : '';
            $btnConfig = adminCreateBtn(array(
                    'label' => ' 编辑',
                    'attr' => array(
                        'href' => getUrl('config/ads/edit').'?id='.$v['id'],
                        'class' => 'btn btn-xs blue-stripe default',
                    ),
                    'tag' => 'a',
                    'permissions' => array(
                        'module' => 'config',
                        'key' => 'ads-edit'
                    )
                ));
            $btnConfig .= ' '.adminCreateBtn(array(
                    'label' => ' 删除',
                    'attr' => array(
                        'href' => getUrl('config/ads/delete').'?id='.$v['id'],
                        'alert-message' => "确认是否删除“ ".$v['ads_name']." ”？",
                        'class' => 'ajax-request-btn btn btn-xs red-stripe default',
                    ),
                    'tag' => 'a',
                    'permissions' => array(
                        'module' => 'config',
                        'key' => 'ads-delete'
                    )
                ));
            $data['aaData'][$k][] = $btnConfig;
        }
        unset($data['data']);
        echo json_encode($data);
    }

    /**
     * 添加
     */
    public function add(){

        $this->loadModel('MerchantAdsModel', 'mMerAds', 'merchant');
        $merchant = (int)get('merchant');

        $position = $this->position;
        $title = '添加';

        $type = (int)get('type');
        if (!$type){
            show_404();
        }
        $backUrl = getUrl('config/ads/home?type='.$type);


        $category = $this->mCategory->getCategoryList(0, true);
        $data = array(
            'position' => $position[$type],
            'merchant' => $merchant,
            'category' => $category,
            'add' => true,
            'title' => $title,
            'type' => $type,
            'backUrl' => $backUrl,
        );
        $this->view('config/ads/from', $data, 'validation,uniform,select2,webuploader,datepicker');
    }

    /**
     * 编辑
     */
    public function edit(){
        $this->loadModel('MerchantAdsModel', 'mMerAds', 'merchant');
        $this->loadModel('MerchantUserModel', 'mMerchant', 'merchant');
        $this->loadModel('ConsumerProductModel', 'mProduct', 'consumer');

        $id = (int)get('id');

        if (!$id){
            show_404();
        }
        $title = '编辑';
        $info = $this->mAds->getInfo($id);
        $position = $this->position;

        $category = $this->mCategory->getCategoryList(0, true);
        // 获取商家店铺名称
        $mInfo = array();
        $param = array();
        if ($info['merchant_id'] > 0) {
            $mInfo = $this->mMerchant->getInfo($info['merchant_id'], 0, true);
        }
        if ($info['type'] == 3 && $info['param'] > 0) {
            $param = $this->mProduct->getInfo($info['param'], $info['merchant_id'], true);
        }
        $data = array(
            'type' => $info['ads_position'],
            'info' => $info,
            'position' => $position[$info['ads_position']],
            'category' => $category,
            'add' => false,
            'tips' => '',
            'mInfo'=> $mInfo,
            'param'=> $param,
            'title' => $title,
            'backUrl' => getUrl('config/ads/home?type='.$info['ads_position']),
        );
        $this->view('config/ads/from', $data, 'validation,select2,webuploader,datepicker');
    }

    /**
     * 保存
     */
    public function save(){
        //表单验证
        $vConf = array(
            array('ads_name', '广告名称', 'required'),
            array('ads_position', '广告位', 'required|in_list[1,2,3,4,5]'),
//            array('starttime', '开始时间', 'required'),
//            array('endtime', '结束时间', 'required'),
        );
        $adsPosition = post('ads_position');
        $type = post('type');
        $url = trim(post('url'));
        $product_id = post('product_id'); // 商品id
        $category_id = post('category_id'); // 分类id
        $merchant_id = post('merchant_id'); // 商家id
        $param = 0;
        if (in_array($adsPosition,array(2,3,4,5))) {
            $vConf[] = array('type', '链接类型', 'required|in_list[0,1,2,3,4]');
            if ($type == 1){
                $vConf[] = array('url', '地址', 'required');
                $merchant_id = 0;
            }else if ($type == 2){
                $vConf[] = array('merchant_id', '商家id', 'required|is_natural_no_zero');
            }else if ($type == 3){
                $vConf[] = array('merchant_id', '商家id', 'required|is_natural_no_zero');
                $vConf[] = array('product_id', '商品id', 'required|is_natural_no_zero');
                $param = $product_id;
            }else if ($type == 4){
                $vConf[] = array('category_id', '分类id', 'required|is_natural_no_zero');
                $param = $category_id;
                $merchant_id = 0;
            }
        }else{
            $type = 0;
            $merchant_id = 0;
        }
        $this->formDataValidation($vConf);
        $id = (int)post('id');


//        $startTime = post('starttime');
//        $endTime = post('endtime');

        $pic = post('pic');
        if (empty($pic)){
            $this->ajaxReturn(0, '请上传广告图片');
        }
//
//        $startTime = strtotime($startTime);
//        $endTime = strtotime($endTime);
//        if (!$startTime || !$endTime) {
//            $this->ajaxReturn(0, '请选择正确的时间');
//        }
//        if (!$id && $startTime < strtotime(date('Y-m-d', time()))) {
//            $this->ajaxReturn(0, '开始时间不得小于今天');
//        }
//        if ($endTime < $startTime) {
//            $this->ajaxReturn(0, '结束时间不得小于开始时间');
//        }


        $data = array(
            'ads_name' => trim(post('ads_name')),
            'ads_position' => $adsPosition,
            'merchant_id' => $merchant_id,
            'url' => $type == 1 ? $url : '',
            'type' => $type,
            'param' => $param,
//            'starttime' => $startTime,
//            'endtime' => $endTime+86400,
        );

        $this->db->trans_begin();
        if( ! $id){
            $data['addtime'] = time();
            if( ! ($id = $this->mAds->save($data))){
                $this->db->trans_rollback();
                $this->ajaxReturn(0, '保存失败');
            }
        }else{
            $info = $this->mAds->getInfo($id);
            if (!$info){
                $this->ajaxReturn(0, '广告不存在');
            }
        }
        $width = '500';
        $height = '500';
        if ($adsPosition == 1){
            $width = '750';
            $height = '320';
        }else if($adsPosition == 2){
            $width = '750';
            $height = '180';
        }else if($adsPosition == 3){
            $width = '375';
            $height = '470';
        }else if($adsPosition == 4 || $adsPosition == 5){
            $width = '375';
            $height = '230';
        }
        $path = 'uploads/ads/'.$id.'/';
        $tA = explode('?', str_replace(base_url(), '', $pic));
        $img = $tA[0];
        if (!file_exists($img)) {
            $this->db->trans_rollback();
            $this->ajaxReturn(0, '图片错误1');
        }
        $img = imageThumb($img, $path, $width, $height);
        if (!$img) {
            $this->db->trans_rollback();
            $this->ajaxReturn(0, '图片错误2');
        }
        $data['pic'] = $img;
        if( ! $this->mAds->save($data, $id)){
            $this->db->trans_rollback();
            $this->ajaxReturn(0, '保存失败');
        }
        $url = trim(post('backUrl'));
        $this->db->trans_commit();
        $this->ajaxReturn(1, '保存成功', null, $url);
    }

    /**
     * 删除
     */
    public function delete(){
        //表单验证
        $vConf = array(
            array('id', 'id', 'required|is_natural_no_zero'),
        );
        $this->formDataValidation($vConf, array('id' => get('id')));
        $id = (int)get('id');
        $info = $this->mAds->getInfo($id);
        if (!$info){
            $this->ajaxReturn(0, '广告不存在或已删除');
        }
        if ($info['merchant_id'] > 0){
            if ($info['endtime'] > strtotime(date('Y-m-d', time()))){
                $this->ajaxReturn(0, '广告投放未结束不能删除');
            }
            $tA = $this->mAds->save(array('is_delete' => 1), $id);
            if (!$tA){
                $this->ajaxReturn(0, '删除失败');
            }
        }else{
            $tA = $this->mAds->deleteAds($id);
            if (!$tA){
                $this->ajaxReturn(0, '删除失败');
            }
        }

        $this->ajaxReturn(1, '删除成功');
    }

    /**
     * 获取状态显示样式
     * @param 	integer $status
     * @param 	bool    $show
     * @return	string
     */
    protected function getStatus($status = null, $show = false){

        $config = array(1 => '已结束', 2 => '投放中');
        if( ! $status){
            return $config;
        }

        if($status && ! isset($config[$status])){
            return '';
        }

        if( ! $show){
            return $config[$status];
        }


        if($status == 1){
            return '<span class="label label-default">'.$config[$status].'</span>';
        }else if($status == 2){
            return '<span class="label label-success">'.$config[$status].'</span>';
        }

        return'';
    }
}
